package com.zimmur.app.mocolink.manage.web.quartz;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zimmur.app.mocolink.domain.model.UserMessage;
import com.zimmur.app.mocolink.domain.vo.UserMessageInfo;
import com.zimmur.app.mocolink.manage.web.util.JPushCommon;
import com.zimmur.app.mocolink.service.IAppUserService;
import com.zimmur.app.mocolink.service.IUserMessageService;

@Component
public class ProcessPushMessage {
	private static Logger log=LoggerFactory.getLogger(ProcessPushMessage.class);
	@Resource
	private IUserMessageService userMessageService;
	@Resource
	private IAppUserService userService;
	@Value("#{spingMvcProperties['JPUSH.MasterSecret']}")
	private String pushMasterSecret;
	@Value("#{spingMvcProperties['JPUSH.AppKey']}")
	private String pushAppkey;
	//是否生产环境
	@Value("#{spingMvcProperties['JPUSH.Production']}")
	private boolean isProduction=false;
	//一次处理消息数
	private static final Integer messageNum=100;
	/**
     * 每隔两分钟执行一次
     * @Scheduled(fixedRate = 2*60*1000) 
     */
	@Scheduled(fixedRate=2*60*1000)
	public void handleUserPushMessage(){
		
		List<UserMessageInfo> userMessagesList = userMessageService.selectNonePushList(messageNum);
		if(userMessagesList!=null && userMessagesList.size()>0){
			List<Integer> pushIds = new ArrayList<>();
			String jsonObj=null;
			try {
				for (UserMessageInfo message : userMessagesList) {
					if(message!=null){
						pushIds.add(message.getMessageId());
						 ObjectMapper mapper = new ObjectMapper();
						jsonObj = mapper.writeValueAsString(message);
						if(message.getPushType()=="one"){
							JPushCommon.Instance(pushMasterSecret, pushAppkey,isProduction).SendNotifyMessage(message.getMsgTitle(), 
									null, jsonObj,1);
						}else if(!StringUtils.isEmpty(message.getMsgTitle()) && !StringUtils.isEmpty(message.getUserDeviceId())){
							JPushCommon.Instance(pushMasterSecret, pushAppkey,isProduction).SendNotifyMessage(message.getMsgTitle(), 
									message.getUserDeviceId(), jsonObj,0);
						}
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
			try {
				if(pushIds.size()>0){
					userMessageService.updateMessagePushStatusByIds(pushIds);
				}
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
		}
		log.info("call handleUserPushMessage");
	}
	
	
}
